#!/usr/bin/env bash
#
# Summary: Set or show the local application-specific sbt version
#
# Usage: sbtenv local <version>
#        sbtenv local --unset
#
# Sets the local application-specific sbt version by writing the
# version name to a file named `.sbt-version`.

set -e
test -n "${SBTENV_DEBUG}" && set -x

# Provide sbtenv completions
if [ "${1}" = "--complete" ]; then
  echo --unset
  echo system
  exec sbtenv-versions --bare
fi

SBTENV_VERSION="${1}"

if [ "${SBTENV_VERSION}" = "--unset" ]; then
  rm -f .sbt-version
elif [ -n "${SBTENV_VERSION}" ]; then
  previous_file="$(SBTENV_VERSION= sbtenv-version-origin || true)"
  sbtenv-version-file-write .sbt-version "${SBTENV_VERSION}"
  if [ "${previous_file}" -ef .sbtenv-version ]; then
    rm -f .sbtenv-version
    { echo "sbtenv: removed existing \`.sbtenv-version\` file and migrated"
      echo "    local version specification to \`.sbt-version\` file"
    } >& 2
  fi
else
  sbtenv-version-file-read .sbt-version ||
    sbtenv-version-file-read .sbtenv-version ||
    { echo "sbtenv: no local version configured for this directory"
      exit 1
    } >& 2
fi

